# MIT License
# 
# Copyright (c) 2024 - present @ ebraid
# 
# Email: 1477153217@qq.com
# QQ: 1477153217
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# dependence tools
LM = tools/lite-manager/lm.exe
FDTC = tools/fdtc/fdtc.exe
ELF2UF2 = tools/elf2uf2/elf2uf2.exe


.PHONY: check_lmmk
ifneq ($(wildcard .lm.mk),)
-include .lm.mk
else
check_lmmk:
	@echo "Please run 'make xxx_defconfig'"
endif

# disable print directory for make
MAKEFLAGS += --no-print-directory

# toolchain
CC_PREFIX ?= 
CC = $(CC_PREFIX)gcc
AS = $(CC_PREFIX)gcc -x assembler-with-cpp
CP = $(CC_PREFIX)objcopy
SZ = $(CC_PREFIX)size
OD = $(CC_PREFIX)objdump
HEX = $(CP) -O ihex
BIN = $(CP) -O binary -S

# build directory
BUILD_DIR := build

# import sub makefile file
-include arch/$(CONFIG_ARCH)/Makefile


$(BUILD_DIR):
	@mkdir $@


# Pseudo command
.PHONY: config distclean clean flash


# Check if the proj.cfg file exists
config: $(LM) .config
	@$(LM) --projcfg .config --lmcfg lm.cfg --out include/config.h --mk .lm.mk --mem 50
	@$(MAKE) clean


# distclean command, delete build directory and .config file
distclean:
	@$(MAKE) clean
	@$(LM) --rm .config
	@$(LM) --rm .lm.mk


# distclean clean
clean:
	@$(LM) --rm $(BUILD_DIR)
	@$(LM) --rm dts/$(CONFIG_ARCH)/*.c


# xxx_defconfig command, copy configs/xxx_defconfig into current directory
%_defconfig: $(LM)
	@$(LM) --cp configs/$(MAKECMDGOALS) .config
	@$(LM) --projcfg .config --lmcfg lm.cfg --out include/config.h --mk .lm.mk --mem 50
	@$(MAKE) clean


dts/$(CONFIG_ARCH)/$(CONFIG_CHIP)-dts.c: $(FDTC) dts/$(CONFIG_ARCH)/$(CONFIG_CHIP).dts
	@echo "build $(CONFIG_CHIP).dts"
	@$(FDTC) dts/$(CONFIG_ARCH)/$(CONFIG_CHIP).dts -c dts/$(CONFIG_ARCH)/$(CONFIG_CHIP)-dts.c


# lite-manager tool build
$(LM):
	@$(MAKE) -C tools/lite-manager -j4


# fdtc tool build
$(FDTC):
	@$(MAKE) -C tools/fdtc -j4


# elf2uf2 tool build
$(ELF2UF2):
	@$(MAKE) -C tools/elf2uf2 -j4